package config

import (
	"net"
	"os"
	"smart-flow/container/logger"

	"go.uber.org/zap"
)

var (
	IpAddr    string
	V6Addr    bool
	TcpPorts  []int
	UdpPorts  []int
	HttpPorts []int
)

func InitRuntime() {
	IpAddr = AppConfig.Container.IpAddr
	if IpAddr == "" {
		IpAddr = getIpAddr()
	}
	if IpAddr == "" {
		os.Exit(1)
	}
	V6Addr = isIpV6(IpAddr)
	TcpPorts = []int{}
	UdpPorts = []int{}
	HttpPorts = []int{}
}

func AddTcpPort(port int) {
	TcpPorts = append(TcpPorts, port)
}

func AddUdpPort(port int) {
	UdpPorts = append(UdpPorts, port)
}

func AddHttpPort(port int) {
	HttpPorts = append(HttpPorts, port)
}

func getIpAddr() string {
	iFace, err := net.InterfaceByName(AppConfig.Container.InterfaceName)
	if err != nil {
		logger.Logger.Error("[容器] 获取机器IP异常", zap.String("interfaceName", AppConfig.Container.InterfaceName), zap.Error(err))
		return ""
	}
	addresses, err := iFace.Addrs()
	if err != nil {
		logger.Logger.Error("[容器] 获取机器IP异常", zap.String("interfaceName", AppConfig.Container.InterfaceName), zap.Error(err))
		return ""
	}
	for _, addr := range addresses {
		ipNet, ok := addr.(*net.IPNet)
		if ok && !ipNet.IP.IsLoopback() && ipNet.IP.To4() != nil {
			return ipNet.IP.String()
		}
	}
	logger.Logger.Error("[容器] 未找到有效的 IPv4 地址", zap.String("interfaceName", AppConfig.Container.InterfaceName))
	return ""
}

func isIpV6(ip string) bool {
	return net.ParseIP(ip).To4() == nil
}
